﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Xml.XPath;

namespace ComicsEditor
{
    public class ReaderFolder : IComicReader
    {
        public readonly string FolderPath;

        private string infoName;
        private SortedList<string, FileInfo> files;

        public ReaderFolder(string FolderPath, string infoName)
        {
            this.FolderPath = FolderPath;
            this.infoName = infoName;

            files = new SortedList<string, FileInfo>();
            DirectoryInfo dir = new DirectoryInfo(FolderPath);
            foreach (string ext in ComicInfo.Extensions)
                foreach (FileInfo info in dir.GetFiles("*" + ext))
                    files.Add(info.Name, info);
        }

        public XPathDocument GetInfo()
        {
            if (File.Exists(FolderPath + Path.DirectorySeparatorChar + infoName))
                return new XPathDocument(FolderPath + Path.DirectorySeparatorChar + infoName);

            StringBuilder sb = new StringBuilder();
            sb.Append("<?xml version=\"1.0\"?>\n");
            sb.Append("<ComicInfo>\n");
            sb.AppendFormat("<PageCount>{0}</PageCount>\n", files.Count);
            sb.Append("<Pages>\n");
            for (int i = 0; i < files.Count; i++)
                sb.AppendFormat("<Page Image=\"{0}\" ImageSize=\"{1}\" Key=\"{2}\" />\n", i, files.Values[i].Length, ComicInfo.XmlEncode(files.Keys[i]));
            sb.Append("</Pages>\n");
            sb.Append("</ComicInfo>\n");

            return new XPathDocument(new StringReader(sb.ToString()));
        }

        public Stream GetStream(string key)
        {
            return File.Open(FolderPath + Path.DirectorySeparatorChar + key, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
        }

        public string GetKey(int index)
        {
            if (index >= files.Count)
                return null;
            return files.Keys[index];
        }
    }
}
